#include "filehashtool.h"
#include <QFile>
#include <QCryptographicHash>
#include <QDir>
#include <QDebug>

FileHashTool::FileHashTool()
{

}

QString FileHashTool::hashOneFile(QString filePath)
{
    qDebug() << "will open file";

    QFile file(filePath); //stFilePath文件的绝对路径
    if(file.open(QIODevice::ReadOnly)) //只读方式打开
    {
        qDebug() << "will hash file";

        QCryptographicHash hash(QCryptographicHash::Md5);
        if(!file.atEnd())
        {
            hash.addData(file.readAll());
            QString  stHashValue;
            stHashValue.append(hash.result().toHex());
            return stHashValue;
        }
    }
    return QString();
}

QString FileHashTool::hashSomeFile(QString fatherPath, QString filePrefix, QString fileType)
{
    QDir dir(fatherPath);
    QStringList nameFilters;
    nameFilters << "*." + fileType;
    QStringList files = dir.entryList(nameFilters, QDir::Files|QDir::Readable, QDir::Name);

    QString hashValues;
    foreach (QString filePath, files)
    {
        if (filePath.contains(filePrefix))
        {
            hashValues += FileHashTool::hashOneFile(fatherPath + "/" + filePath);
            qDebug() << "child file hashs:" + hashValues;
        }
    }

    QCryptographicHash hash(QCryptographicHash::Md5);
    hash.addData(hashValues.toLatin1());
    QString  stHashValue;
    stHashValue.append(hash.result().toHex());
    return stHashValue;
}
